package com.zjxny.service.impl;

import com.zjxny.service.AccountService;
import lombok.extern.slf4j.Slf4j;
import org.quartz.SchedulerException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import xyz.erupt.job.model.EruptJob;
import xyz.erupt.job.service.EruptJobService;
import xyz.erupt.jpa.dao.EruptDao;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Slf4j
@Service
public class AccountServiceImpl implements AccountService {

    @Resource
    private EruptJobService eruptJobService;

    @Resource
    private EruptDao eruptDao;

    @Resource
    private JdbcTemplate jdbcTemplate;

    @Override
    public void disableAccount(String taskName, Long id) {
        Optional<EruptJob> eruptJobOpt = eruptDao.queryEntityList(EruptJob.class).stream()
                .filter(s -> taskName.equals( s.getName()))
                .findFirst();
        if (eruptJobOpt.isPresent()) {
            if (eruptJobOpt.get().getStatus()) {
                jdbcTemplate.update("update e_job set status=0 where id = " + eruptJobOpt.get().getId());
            }

            try {
                eruptJobService.deleteJob(eruptJobOpt.get());
            } catch (SchedulerException ex) {
                ex.printStackTrace();
            }
        }

        //清除账号中的token
        jdbcTemplate.update("update account_info set cookies='' where id = " + id);
    }

    @Override
    public List<Map<String, Object>> getTaskAccount() {
        String sql = "select id,has_operation,simple_title,cookies,domain,has_biz,has_not_operation from account_info where is_valid=1 and task_status=1 and LENGTH(cookies)>0";
        log.info("getTaskAccount.sql={}",sql);
        List<Map<String, Object>> result = jdbcTemplate.queryForList(sql);
        return result;
    }

    @Override
    public List<Map<String, Object>> getAccountWithCookies() {
        String sql = "select id,has_operation,simple_title,cookies,domain,has_biz,has_not_operation from account_info where is_valid=1 and LENGTH(cookies)>0";
        log.info("getTaskAccount.sql={}",sql);
        List<Map<String, Object>> result = jdbcTemplate.queryForList(sql);
        return result;
    }

    @Override
    public int disableAccount(Long id) {
       return jdbcTemplate.update("update account_info set cookies='' where id = " + id);
    }

    @Override
    public int updateTaskStatus(Long id, Integer status) {
        int affectNum =  jdbcTemplate.update("update account_info set task_status="+status+" where id = " + id);

        log.info("accountService.updateTaskStatus  affectNum={}",affectNum);
        return affectNum;
    }
}
